package com.mingliqiye.minecraft.enchantment.conflict.forge;

import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigPair;
import com.mingliqiye.minecraft.enchantment.conflict.common.MinecraftMod;
import com.mingliqiye.minecraft.enchantment.conflict.common.WebConfigCoreMeMethod;
import com.mingliqiye.minecraft.enchantment.conflict.common.enchantment.EnchantmentEntity;
import com.mingliqiye.minecraft.enchantment.conflict.forge.network.message.ConfigMessage;
import java.util.List;
import java.util.Map;

import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraftforge.fml.ModList;

public class ForgeWebConfigCoreMeMethod implements WebConfigCoreMeMethod {

    @Override
    public void reloadConfig() {}

    @Override
    public Map<String, ConfigPair> getDefConfig() {
        return ForgeMod.CONFIGMANAGER.getDefConfig().getConfig();
    }

    @Override
    public Map<String, ConfigPair> getConfig() {
        return ForgeMod.CONFIGMANAGER.getConfig();
    }

    @Override
    public String getGameVersions() {
        return ModList.get()
            .getModContainerById("minecraft")
            .map((mod) -> mod.getModInfo().getVersion().toString())
            .orElse("未知版本");
    }

    @Override
    public String getModVersions() {
        return ModList.get()
            .getModContainerById(MinecraftMod.MOD_ID)
            .map((mod) -> mod.getModInfo().getVersion().toString())
            .orElse("未知版本");
    }

    @Override
    public String getLoaderVersions() {
        return ModList.get()
            .getModContainerById("forge")
            .map((mod) -> mod.getModInfo().getVersion().toString())
            .orElse("未知版本");
    }

    @Override
    public String getLoaderName() {
        return "Forge";
    }

    @Override
    public List<EnchantmentEntity> getAllEnchantments() {
        Registry<Enchantment> enchantments = ForgeMod.SERVER.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
        return enchantments.stream().map((a) -> {
            var sid = enchantments.getKey(a);
            return new EnchantmentEntity(sid.getNamespace() + ":" + sid.getPath(), null, a.description().getString(),
                    enchantments.getId(a));
        }).toList();
    }

    @Override
    public boolean getTest(Integer fid, Integer sid) {
        Registry<Enchantment> enchantments = ForgeMod.SERVER.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
        var f = enchantments.asHolderIdMap().byId(fid);
        var s = enchantments.asHolderIdMap().byId(sid);
        return Enchantment.areCompatible(f, s);
    }

    @Override
    public void saveConfig(Map<String, ConfigPair> configPairMap) {
        ForgeMod.CONFIGMANAGER.setConfig(configPairMap);
        ForgeMod.CONFIGMANAGER.save();
        ConfigMessage.sendAll(configPairMap);
    }
}
